package com.cans.base.service.impl;

import com.cans.base.config.CansFileProperties;
import com.cans.base.dao.IFileDetailDao;
import com.cans.base.dao.api.IBaseDao;
import com.cans.base.model.FileDetail;
import com.cans.base.model.SsoUser;
import com.cans.base.service.api.IFileDetailService;
import com.cans.base.utils.FilePathUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author cans
 * @date 2018/6/4
 * @description 文件操作业务层
 */
@Service("fileDetailService")
@Transactional(rollbackFor = Exception.class)
public class FileDetailServiceImpl extends BaseServiceImpl<FileDetail,String>  implements IFileDetailService {

    @Resource
    private IFileDetailDao fileDetailDao;
    @Resource
    private CansFileProperties cansFileProperties;

    @Override
    public IBaseDao<FileDetail, String> getDaoImpl() {
        return fileDetailDao;
    }

    /**
     * 保存文件到服务器
     * @param file
     */
    @Override
    public FileDetail saveFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = cansFileProperties.getBasePath() + FilePathUtil.generateFilePathByDate() ;



        // 将文件信息存入数据库
        FileDetail fileDetail = new FileDetail();
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        SsoUser user = (SsoUser)request.getSession().getAttribute("ssoUser");

        // 文件名
        fileDetail.setFileName(fileName);
        // 文件类型
        String type = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        fileDetail.setFileType(type);

        // 上传人员ID
        fileDetail.setUploadUserId(user.getId());
        // 保存
        this.save(fileDetail);

        // 文件路劲
        String saveFileName = fileDetail.getId() + "." + type;
        fileDetail.setUrl(path + saveFileName);

        // 将文件存入磁盘
        File dest = new File(path, saveFileName);
        //判断文件父目录是否存在
        if(!dest.getParentFile().exists() && !dest.getParentFile().mkdirs()){
            throw new RuntimeException("目录创建失败:" + path);
        }
        //保存文件
        file.transferTo(dest);

        return fileDetail;
    }
}
